import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/guide/sysmodel.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/mine_setting/mine_setting.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_pickers/CropConfig.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:shared_preferences/shared_preferences.dart';

///
/// 照片墙
///
class MineBackgroundPage extends StatefulWidget {

  final SharedUserInfo friendInfo;//设置好友聊天背景

  const MineBackgroundPage({Key key, this.friendInfo}) : super(key: key);  //好友的电话号码

  @override
  _MineBackgroundPageState createState() => _MineBackgroundPageState();
}

class _MineBackgroundPageState extends State<MineBackgroundPage> {

  SharedUserInfo userInfo = SharedUserInfo();
  List<LaunchModel> list = [];
  bool isupdate = false;

  @override
  void initState() {
    super.initState();

    _initData();
  }

  void _initData() async {
    SharedPreferences share = await SharedPreferences.getInstance();
    final str = share.getString(KEY_SYS_Data);
    final model = SysModel.fromJson(json.decode(str));
    setState(() {
      list.addAll(model.longback);
    });
  }

  _photo() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if(image != null){
      widget.friendInfo == null ? _uploadImage(image) : _requestChangeChatBackgroud(image);
    }
  }

  _album() {
    ImagePickers.pickerPaths(
      galleryMode: GalleryMode.image,
      selectCount: 1,
      showCamera: false,
      cropConfig :CropConfig(enableCrop: true,height: 2,width: 1),
    ).then((value){
      if(value != null && value.length != 0) {
        final image = File(value.first.path);
        if(image != null){ // 如果传入了friend,代表是设置聊天背景
          widget.friendInfo == null ? _uploadImage(image) : _requestChangeChatBackgroud(image);
        }
      }
    });
  }

  _uploadImage(File image) {
    AlertTool.showLoadingDialog(context,"正在上传...");
    Networktool.uploadImage(API.longback, image, (data) async {
      print("$data");
      AlertTool.showToast("修改成功");
      if(data["data"] != null) {
        isupdate = true;
        SharedUserInfo.saveData(data);
      }
    },
    fail: (msg) => AlertTool.showToast(msg),
    finaly: () => Navigator.of(context).pop()
    );
  }

  _requestChangeChatBackgroud(File image) {
    AlertTool.showLoadingDialog(context,"正在上传...");
    Networktool.uploadImage(API.frienchatback, image, (data) async {
      print("$data");
      isupdate = true;
      AlertTool.showToast("修改成功");
    },
    params: {"mobile": widget.friendInfo.mobile},
    fail: (msg) => AlertTool.showToast(msg),
    finaly: () => Navigator.of(context).pop()
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff9f9f9),
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Text("自定义背景"),
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop(isupdate);
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
      ),
      body: Container(
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5)
              ),
              child: Column(
                children: [
                  GestureDetector(
                    onTap: _album,
                    child: MineSettingCell("从手机相册选择")
                  ),
                  GestureDetector(
                    onTap: _photo,
                    child: MineSettingCell("拍一张")
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 20, bottom: 10),
              child: Text("推荐背景", style: instanceTextStyle(11, APP_font_grey),),
            ),

            Expanded(
              child: BackgroundWarpWidget(
                list: list ?? [],
                friendInfo: widget.friendInfo,
                callback: (){
                  isupdate = true;
                },
              )
            )
          ],
        ),
      ),
    );
  }
}

class BackgroundWarpWidget extends StatefulWidget {

  final List<LaunchModel> list;
  final Function callback;
  final SharedUserInfo friendInfo; // 如果不为空则是设置好友聊天背景

  BackgroundWarpWidget({Key key, this.list, this.callback, this.friendInfo}) : super(key: key);

  @override
  _BackgroundWarpWidgetState createState() => _BackgroundWarpWidgetState();
}

class _BackgroundWarpWidgetState extends State<BackgroundWarpWidget> {

  String userUrl;


  _request(String url) {
    if(userUrl == url) return;
    setState(() {
      userUrl = url;
    });
    widget.friendInfo == null ? _updatelongback() : _requestChangeChatBackgroud();
  }

  _updatelongback() {
    Networktool.request(API.edit, params: {"longback": userUrl}, success: (data){
      print(data);
      if(data["data"] != null) {
        SharedUserInfo.saveData(data);
        AlertTool.showToast("修改成功");
        if(widget.callback != null) widget.callback();
      }
    },
    fail: (msg) => AlertTool.showToast(msg));
  }

  _requestChangeChatBackgroud() {
    Networktool.request(API.frienchatback, params: {"mobile": widget.friendInfo.mobile, "url": userUrl}, success: (data){
      AlertTool.showToast("修改成功");
      if(widget.callback != null) widget.callback();
    });
  }

  @override
  void initState() {
    super.initState();
    _initData();
  }

  _initData() async {
    if(widget.friendInfo == null){
      final user = await SharedUserInfo.instance();
      userUrl = user.longback;
    } else {
      userUrl = widget.friendInfo.chatback;
    }
    
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5)
      ),
      child: GridView.builder(
        itemCount: widget.list.length,
        padding: const EdgeInsets.fromLTRB(25, 15, 18, 25),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, mainAxisSpacing: 20, crossAxisSpacing: 20, childAspectRatio: 0.45), 
        itemBuilder: (context, index){
          final imageUrl = widget.list[index].url;
          var issetting = userUrl == imageUrl;
          return Container(
            child: Column(
              children: [
                Expanded(
                  child: PhysicalModel(
                    color: Colors.white,
                    clipBehavior: Clip.antiAlias,
                    borderRadius: BorderRadius.circular(10),
                    child: CachedNetworkImage(
                        imageUrl: imageUrl,
                        fit: BoxFit.cover,
                        placeholder: (context, url) => Center(child: CircularProgressIndicator()),
                        errorWidget: (context, url, error) => Icon(Icons.error),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  child: Text(widget.list[index].name ?? "",style: instanceTextStyle(14, APP_font_black),),
                ),
                GestureDetector(
                  onTap: (){
                    _request(imageUrl);
                  },
                  child: MineBackgroundSettingButton(issetting: issetting,)
                )
              ],
            ),
          );
      }),
    );
  }
}

class MineBackgroundSettingButton extends StatelessWidget {

  final bool issetting;

  const MineBackgroundSettingButton({Key key, this.issetting}) : super(key: key);

  @override
  Widget build(BuildContext context) {
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 18.5, vertical: 4),
        decoration: BoxDecoration(
          border: Border.all(color:issetting ? const Color(0xffdddddd) : APP_main_color, width: 0.5),
          color: issetting ? const Color(0xffdddddd): Colors.white,
          borderRadius: BorderRadius.circular(20)
        ),
        child: Text(
          "设置",
          style: instanceTextStyle(12, APP_font_black),
        ),
    );
  }
}